package com.yu.mall.controller;

import java.io.File;
import java.io.FileOutputStream;
import java.net.MalformedURLException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import com.yu.mall.util.URLUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.yu.mall.dto.BaseDTO;
import com.yu.mall.entity.CardVolume;
import com.yu.mall.entity.HomePage;
import com.yu.mall.entity.LunboImg;
import com.yu.mall.entity.ProductInfo;
import com.yu.mall.entity.TypeImg;
import com.yu.mall.mapper.HomePageMapper;
import com.yu.mall.mapper.LunboImgMapper;
import com.yu.mall.mapper.ProductInfoMapper;
import com.yu.mall.mapper.TypeImgMapper;
import com.yu.mall.service.ProductService;
import com.yu.mall.service.UserService;
import com.yu.mall.util.ResultUtils;
import com.yu.mall.vo.ResultVO;
import com.yu.mall.vo.user.UserVO;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import tk.mybatis.mapper.entity.Example;
import tk.mybatis.mapper.entity.Example.Criteria;

@RestController
@RequestMapping("HomePage")
@Api(tags = "商城首页管理", value = "商城首页管理")
public class HomePageController {

	@Autowired
	private HomePageMapper homePageMapper;
	
	@Autowired
	private ProductInfoMapper productInfoMapper;
	
	@Autowired
	private ProductService productService;
	
	@Autowired
	private TypeImgMapper typeImgMapper;
	
	@Autowired
	private LunboImgMapper lunboImgMapper;
	
	@Autowired
	private UserService userService;
	
	@PostMapping("addHomePage")
	@ApiOperation(value = "添加首页配置")
	@ApiImplicitParams({ @ApiImplicitParam(name = "lunbo", value = "轮播商品id多个用逗号隔开", dataType = "String"),
			@ApiImplicitParam(name = "categoryId", value = "类目多个用逗号隔开", dataType = "String") ,
			@ApiImplicitParam(name = "hotcommodity", value = "热门商品id多个用逗号隔开", dataType = "String") })
	public ResultVO addHomePage(String lunbo, String categoryId, String hotcommodity) {
		if (lunbo == null || "".equals(lunbo)) {
			return ResultUtils.error("轮播商品不能为空");
		}

		if (categoryId == null || "".equals(categoryId)) {
			return ResultUtils.error("类目不能为空");
		}
		if (hotcommodity == null || "".equals(hotcommodity)) {
			return ResultUtils.error("热门商品不能为空");
		}
		
		HomePage homePage = new HomePage();
		homePage.setLunbo(lunbo);
		homePage.setCategory(categoryId);
		homePage.setHotcommodity(hotcommodity);
		homePage.setIstag("1");
		homePageMapper.insert(homePage);
		return ResultUtils.success("添加成功!");
	}
	
	@PostMapping("updateHomePage")
	@ApiOperation(value = "修改首页配置")
	@ApiImplicitParams({ @ApiImplicitParam(name = "lunbo", value = "轮播商品id多个用逗号隔开", dataType = "String"),
			@ApiImplicitParam(name = "categoryId", value = "类目list多个用逗号隔开", dataType = "String") ,
			@ApiImplicitParam(name = "hotcommodity", value = "热门商品id多个用逗号隔开", dataType = "String"),
			@ApiImplicitParam(name = "id", value = "id",example = "1")})
	public ResultVO updateHomePage(int id,String lunbo, String categoryId, String hotcommodity) {
		if (String.valueOf(id).equals("")) {
			return ResultUtils.error("id不能为空");
		}
		HomePage homePage = new HomePage();
		if (lunbo != null && !"".equals(lunbo)) {
			homePage.setLunbo(lunbo);
		}

		if (categoryId != null && !"".equals(categoryId)) {
			homePage.setCategory(categoryId);
		}
		if (hotcommodity != null && !"".equals(hotcommodity)) {
			homePage.setHotcommodity(hotcommodity);
		}
		homePage.setIstag("1");
		homePage.setId(id);
		homePageMapper.updateByPrimaryKey(homePage);
		
		return ResultUtils.success("修改成功!");
	}
	
	@GetMapping("getWXHomePage")
	@ApiOperation(value = "获取小程序首页配置")
	public ResultVO getWXHomePage(BaseDTO baseDTO) {
		HashMap<String, Object> hashMap = new HashMap<String, Object>();
		if(!"".equals(baseDTO.getOpenid()) && baseDTO.getOpenid() !=null) {
			ResultVO<UserVO> resultVO = userService.get(baseDTO.getOpenid());
			UserVO data = resultVO.getData();
			if("1".equals(data.getIsCard())) {
				HomePage homePage = homePageMapper.selectByPrimaryKey(2);
				String lunbo = homePage.getLunbo();
				String hotcommodity = homePage.getHotcommodity();
				ArrayList<ProductInfo> lunboInfoList = new ArrayList<ProductInfo>();
				ArrayList<ProductInfo> hotcommodityInfoList = new ArrayList<ProductInfo>();
				List<String> lunboList = Arrays.asList(lunbo.split(","));
				if(lunboList !=null && lunboList.size()>0) {
					for (String string : lunboList) {
						ProductInfo productInfo = productInfoMapper.selectByPrimaryKey2(string);
						if(productInfo != null) {
						Example example = new Example(LunboImg.class);
						Criteria createCriteria = example.createCriteria();
						createCriteria.andEqualTo("skuid", productInfo.getSkuId());
						createCriteria.andEqualTo("type", "1");
						try {
							productInfo.setImagePath(lunboImgMapper.selectByExample(example).get(0).getUrl());
						} catch (Exception e) {
							// TODO: handle exception
							productInfo.setImagePath("");
						}
						lunboInfoList.add(productInfo);
						}
					}
				}
				List<String> hotcommodityList = Arrays.asList(hotcommodity.split(","));
				if(hotcommodityList !=null && hotcommodityList.size()>0) {
				for (String string : hotcommodityList) {
					ProductInfo productInfo = productInfoMapper.selectByPrimaryKey2(string);
					if(productInfo != null) {
					hotcommodityInfoList.add(productInfo);
					}
				}
				}
				hashMap.put("lunboList", lunboInfoList);
				hashMap.put("hotcommodityList", hotcommodityInfoList);
			}else {
				HomePage homePage = homePageMapper.selectByPrimaryKey(1);
				String lunbo = homePage.getLunbo();
				String category = homePage.getCategory();
				String hotcommodity = homePage.getHotcommodity();
				ArrayList<ProductInfo> lunboInfoList = new ArrayList<ProductInfo>();
				ArrayList<HashMap<String, Object>> categoryInfoList = new ArrayList<HashMap<String, Object>>();
				ArrayList<ProductInfo> hotcommodityInfoList = new ArrayList<ProductInfo>();
				List<String> lunboList = Arrays.asList(lunbo.split(","));
				if(lunboList !=null && lunboList.size()>0) {
					for (String string : lunboList) {
						ProductInfo productInfo = productInfoMapper.selectByPrimaryKey2(string);
						if(productInfo != null) {
						Example example = new Example(LunboImg.class);
						Criteria createCriteria = example.createCriteria();
						createCriteria.andEqualTo("skuid", productInfo.getSkuId());
						createCriteria.andEqualTo("type", "0");
						productInfo.setImagePath(lunboImgMapper.selectByExample(example).get(0).getUrl());
						lunboInfoList.add(productInfo);
						}
					}
				}
				List<String> categoryList = Arrays.asList(category.split(","));
				Map<String, String> allProductType = productService.getAllProductType();
				for (String categoryId : categoryList) {
					HashMap<String, Object> hashMap2 = new HashMap<String, Object>();
					hashMap2.put("id", categoryId);
					hashMap2.put("name", allProductType.get(categoryId));
					Example example = new Example(CardVolume.class);
					Criteria createCriteria = example.createCriteria();
					createCriteria.andEqualTo("id", categoryId);
					try {
						hashMap2.put("url", typeImgMapper.selectByExample(example).get(0).getUrl());
					} catch (Exception e) {
						// TODO: handle exception
						hashMap2.put("url", "");
					}
					categoryInfoList.add(hashMap2);
				}
				List<String> hotcommodityList = Arrays.asList(hotcommodity.split(","));
				if(hotcommodityList !=null && hotcommodityList.size()>0) {
				for (String string : hotcommodityList) {
					ProductInfo productInfo = productInfoMapper.selectByPrimaryKey2(string);
					if(productInfo != null) {
					hotcommodityInfoList.add(productInfo);
					}
				}
				}
				hashMap.put("lunboList", lunboInfoList);
				hashMap.put("categoryList", categoryInfoList);
				hashMap.put("hotcommodityList", hotcommodityInfoList);
			}
		}else {
			HomePage homePage = homePageMapper.selectByPrimaryKey(1);
			String lunbo = homePage.getLunbo();
			String category = homePage.getCategory();
			String hotcommodity = homePage.getHotcommodity();
			ArrayList<ProductInfo> lunboInfoList = new ArrayList<ProductInfo>();
			ArrayList<HashMap<String, Object>> categoryInfoList = new ArrayList<HashMap<String, Object>>();
			ArrayList<ProductInfo> hotcommodityInfoList = new ArrayList<ProductInfo>();
			List<String> lunboList = Arrays.asList(lunbo.split(","));
			if(lunboList !=null && lunboList.size()>0) {
				for (String string : lunboList) {
					ProductInfo productInfo = productInfoMapper.selectByPrimaryKey2(string);
					if(productInfo != null) {
					Example example = new Example(LunboImg.class);
					Criteria createCriteria = example.createCriteria();
					createCriteria.andEqualTo("skuid", productInfo.getSkuId());
					createCriteria.andEqualTo("type", "0");
					try {
						productInfo.setImagePath(lunboImgMapper.selectByExample(example).get(0).getUrl());
					} catch (Exception e) {
						// TODO: handle exception
						productInfo.setImagePath("");
					}
					lunboInfoList.add(productInfo);
					}
				}
			}
			List<String> categoryList = Arrays.asList(category.split(","));
			Map<String, String> allProductType = productService.getAllProductType();
			for (String categoryId : categoryList) {
				HashMap<String, Object> hashMap2 = new HashMap<String, Object>();
				hashMap2.put("id", categoryId);
				hashMap2.put("name", allProductType.get(categoryId));
				Example example = new Example(CardVolume.class);
				Criteria createCriteria = example.createCriteria();
				createCriteria.andEqualTo("id", categoryId);
				try {
					hashMap2.put("url", typeImgMapper.selectByExample(example).get(0).getUrl());
				} catch (Exception e) {
					// TODO: handle exception
					hashMap2.put("url", "");
				}
				categoryInfoList.add(hashMap2);
			}
			List<String> hotcommodityList = Arrays.asList(hotcommodity.split(","));
			if(hotcommodityList !=null && hotcommodityList.size()>0) {
			for (String string : hotcommodityList) {
				ProductInfo productInfo = productInfoMapper.selectByPrimaryKey2(string);
				if(productInfo != null) {
				hotcommodityInfoList.add(productInfo);
				}
			}
			}
			hashMap.put("lunboList", lunboInfoList);
			hashMap.put("categoryList", categoryInfoList);
			hashMap.put("hotcommodityList", hotcommodityInfoList);
		}
		return ResultUtils.success(hashMap);
	}
	
	
	@GetMapping("getHomePage")
	@ApiOperation(value = "获取首页配置")
	@ApiImplicitParam(name = "id",value="id",required=true,example = "1")
	public ResultVO getHomePage(int id) {
		if (String.valueOf(id).equals("")) {
			return ResultUtils.error("id不能为空");
		}
		HomePage homePage = homePageMapper.selectByPrimaryKey(id);
		String lunbo = homePage.getLunbo();
		String category = homePage.getCategory();
		String hotcommodity = homePage.getHotcommodity();
		HashMap<String, Object> hashMap = new HashMap<String, Object>();
		ArrayList<ProductInfo> lunboInfoList = new ArrayList<ProductInfo>();
		ArrayList<HashMap<String, Object>> categoryInfoList = new ArrayList<HashMap<String, Object>>();
		ArrayList<ProductInfo> hotcommodityInfoList = new ArrayList<ProductInfo>();
		List<String> lunboList = Arrays.asList(lunbo.split(","));
		if(lunboList !=null && lunboList.size()>0) {
			for (String string : lunboList) {
				ProductInfo productInfo = productInfoMapper.selectByPrimaryKey2(string);
				if(productInfo != null) {
					Example example = new Example(LunboImg.class);
					Criteria createCriteria = example.createCriteria();
					createCriteria.andEqualTo("skuid", productInfo.getSkuId());
					if(id==1) {
						createCriteria.andEqualTo("type", "0");
					}else {
						createCriteria.andEqualTo("type", "1");
						}
					try {
						productInfo.setImagePath(lunboImgMapper.selectByExample(example).get(0).getUrl());
					} catch (Exception e) {
						// TODO: handle exception
						productInfo.setImagePath("");
					}
					lunboInfoList.add(productInfo);
				}
			}
		}
		if(id==1) {
			if(category !=null && !"".equals(category)){
				List<String> categoryList = Arrays.asList(category.split(","));
				Map<String, String> allProductType = productService.getAllProductType();
				for (String categoryId : categoryList) {
					HashMap<String, Object> hashMap2 = new HashMap<String, Object>();
					hashMap2.put("id", categoryId);
					hashMap2.put("name", allProductType.get(categoryId));
					Example example = new Example(CardVolume.class);
					Criteria createCriteria = example.createCriteria();
					createCriteria.andEqualTo("id", categoryId);
					try {
						hashMap2.put("url", typeImgMapper.selectByExample(example).get(0).getUrl());
					} catch (Exception e) {
						// TODO: handle exception
						hashMap2.put("url", "");
					}
					categoryInfoList.add(hashMap2);
				}
			}
		}
		
		List<String> hotcommodityList = Arrays.asList(hotcommodity.split(","));
		if(hotcommodityList !=null && hotcommodityList.size()>0) {
		for (String string : hotcommodityList) {
			ProductInfo productInfo = productInfoMapper.selectByPrimaryKey2(string);
			hotcommodityInfoList.add(productInfo);
		}
		}
		hashMap.put("lunboList", lunboInfoList);
		hashMap.put("categoryList", categoryInfoList);
		hashMap.put("hotcommodityList", hotcommodityInfoList);
		return ResultUtils.success(hashMap);
	}
	
	@PostMapping("delHomePage")
	@ApiOperation(value = "删除首页配置")
	@ApiImplicitParam(name = "id",value="id",required=true,example = "1")
	public ResultVO delHomePage(int id) {
		if (String.valueOf(id).equals("")) {
			return ResultUtils.error("id不能为空");
		}
		homePageMapper.deleteByPrimaryKey(id);
		return ResultUtils.success("删除成功!");
	}
	
	/**
     * @Title:图片上传   
     * @Description
     * @param MultipartFile，request
     * @return
     * @throws
     */
    @PostMapping("upload")
	@ApiOperation(value = "上传/修改类目图片")
	@ApiImplicitParams({ @ApiImplicitParam(name = "files", value = "file文件", dataType = "MultipartFile"),
			@ApiImplicitParam(name = "request", value = "request", dataType = "HttpServletRequest"),
			@ApiImplicitParam(name = "categoryId", value = "类目id", dataType = "String"),
			@ApiImplicitParam(name = "name", value = "类目名称", dataType = "String")
			})
    public ResultVO upload(MultipartFile files,String categoryId,String name,HttpServletRequest request) throws MalformedURLException {
		String url = "http://" + URLUtils.getHost(request.getRequestURL().toString()) + "/";
        String dicName="category";//服务器上传文件夹名称
        String newFileName=files.getOriginalFilename();    
        newFileName=newFileName.substring(0,newFileName.lastIndexOf("."));
        String picurl = saveFile(files,newFileName,dicName, request);
        TypeImg selectByPrimaryKey = typeImgMapper.selectByPrimaryKey(categoryId);
        if(selectByPrimaryKey!=null) {
        	typeImgMapper.delete(selectByPrimaryKey);
        	}
        TypeImg typeImg = new TypeImg();
        typeImg.setId(categoryId);
        typeImg.setName(name);
        typeImg.setUrl(url + picurl);
        typeImgMapper.insert(typeImg);
        return ResultUtils.success(typeImg.getUrl());
    }
    
	/**
     * @Title:图片上传   
     * @Description
     * @param MultipartFile，request
     * @return
     * @throws
     */
    @PostMapping("uploadLunBo")
	@ApiOperation(value = "上传/修改类目图片")
	@ApiImplicitParams({ @ApiImplicitParam(name = "files", value = "file文件", dataType = "MultipartFile"),
			@ApiImplicitParam(name = "request", value = "request", dataType = "HttpServletRequest"),
			@ApiImplicitParam(name = "skuid", value = "商品id", dataType = "String"),
			@ApiImplicitParam(name = "type", value = "0：正常首页轮播 1：劳保首页轮播", dataType = "String")
			})
    public ResultVO uploadLunBo(MultipartFile file,String skuid,String type,HttpServletRequest request) throws MalformedURLException {
		String url = "http://" + URLUtils.getHost(request.getRequestURL().toString()) + "/";
		String dicName="lunbo";//服务器上传文件夹名称
        String newFileName=file.getOriginalFilename();
        newFileName=newFileName.substring(0,newFileName.lastIndexOf("."));
        String picurl = saveFile(file,newFileName,dicName, request);
        
        Example example = new Example(LunboImg.class);
		Criteria createCriteria = example.createCriteria();
		if(!"".equals(skuid) && skuid !=null) {
			createCriteria.andEqualTo("skuid", skuid);
		}else {
			 return ResultUtils.error("skuid不能为空");
		}
		if(!"".equals(type) && type !=null) {
			createCriteria.andEqualTo("type", type);
		}else {
			 return ResultUtils.error("type不能为空");
		}
        List<LunboImg> selectByExample = lunboImgMapper.selectByExample(example);
        if(selectByExample!=null&&selectByExample.size()>0) {
        	lunboImgMapper.delete(selectByExample.get(0));
        	}
        LunboImg lunboImg = new LunboImg();
        lunboImg.setSkuid(skuid);
        lunboImg.setType(type);
        lunboImg.setUrl(url + picurl);
        lunboImgMapper.insert(lunboImg);
        return ResultUtils.success(lunboImg.getUrl());
    }
    
	@PostMapping("delLunBo")
	@ApiOperation(value = "删除轮播图")
	@ApiImplicitParams({
		@ApiImplicitParam(name = "skuid", value = "商品id", dataType = "String"),
		@ApiImplicitParam(name = "type", value = "0：正常首页轮播 1：劳保首页轮播", dataType = "String")
		})
	public ResultVO delLunBo(String skuid,String type) {
        Example example = new Example(LunboImg.class);
		Criteria createCriteria = example.createCriteria();
		if(!"".equals(skuid) && skuid !=null) {
			createCriteria.andEqualTo("skuid", skuid);
		}else {
			 return ResultUtils.error("skuid不能为空");
		}
		if(!"".equals(type) && type !=null) {
			createCriteria.andEqualTo("type", type);
		}else {
			 return ResultUtils.error("type不能为空");
		}
		lunboImgMapper.deleteByExample(example);
		return ResultUtils.success("删除成功!");
	}
    
	/**
     * @Title:类目图片查询列表 
     * @Description
     * @return
     * @throws
     */
    @GetMapping("queryTypeImgList")
	@ApiOperation(value = "类目图片查询列表 ")
    public ResultVO queryTypeImgList() {
    	List<TypeImg> selectAll = typeImgMapper.selectAll();
        return ResultUtils.success(selectAll);
    }
    
	/**
     * @Title:类目图片查询
     * @Description
     * @param MultipartFile，request
     * @return
     * @throws
     */
    @GetMapping("queryTypeImgById")
	@ApiOperation(value = "类目图片查询 ")
    @ApiImplicitParam(name = "categoryId",value="类目id",required=true)
    public ResultVO queryTypeImgById(String categoryId) {
        TypeImg selectByPrimaryKey = typeImgMapper.selectByPrimaryKey(categoryId);
        return ResultUtils.success(selectByPrimaryKey);
    }
    
	/**
     * @Title:所有类目图片查询
     * @Description
     * @return
     * @throws
     */
    @GetMapping("queryTypeImgAll")
	@ApiOperation(value = "所有类目图片查询 ")
    public ResultVO queryTypeImgAll() {
    	JSONArray result = new JSONArray();
        Map<String, String> allProductType = productService.getAllProductType();
        for (Map.Entry<String, String> entry : allProductType.entrySet()) {
            JSONObject item = new JSONObject();
            item.put("id", entry.getKey());
            item.put("name", entry.getValue());
            TypeImg selectByPrimaryKey = typeImgMapper.selectByPrimaryKey(entry.getKey());
            if(selectByPrimaryKey !=null) {
            	item.put("url", selectByPrimaryKey.getUrl());
            }else {
            	item.put("url", "");
            }
            result.add(item);
        }
        return ResultUtils.success(result);
    }
    
    
    public static String saveFile(MultipartFile filedata,String newFileName,String dicName, HttpServletRequest request) {
        Calendar cale = null;
       cale = Calendar.getInstance();  
       String year = String.valueOf(cale.get(Calendar.YEAR));  
       String month = String.valueOf(cale.get(Calendar.MONTH) + 1);
       String base = "/admin/";
        String saveFilePath =  "UpFile/"+dicName+"/"+year+"/"+month+"/";
        /* 构建文件目录 */
        File fileDir = new File(base + saveFilePath);
        if (!fileDir.exists()) {
            fileDir.mkdirs();
        }
        // 上传的文件名
        String filename = filedata.getOriginalFilename();
        // 文件的扩张名
        String extensionName = filename.substring(filename.lastIndexOf(".") + 1);
        try {
            String imgPath = base + saveFilePath + newFileName + "." + extensionName;
            // System.out.println(pathval + imgPath);打印图片位置
            FileOutputStream out = new FileOutputStream(imgPath);
            // 写入文件
            out.write(filedata.getBytes());
            out.flush();
            out.close();
            return saveFilePath + newFileName + "." + extensionName;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
	
}
